<template>
  <div class="app-container">
    <analyze></analyze>
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="68px" size="mini">
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="queryParams.projectName" clearable placeholder="请输入" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="加班类型" prop="overtimeType">
        <el-select v-model="queryParams.overtimeType" clearable placeholder="请选择" @keyup.enter.native="handleQuery">
          <el-option v-for="dict in overtimeTypeOptions" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="加班月份" prop="overtimeMonth">
        <el-date-picker v-model="queryParams.overtimeMonth" clearable placeholder="请选择" type="month" value-format="yyyy-MM"></el-date-picker>
      </el-form-item>
      <el-form-item label="员工姓名" prop="staffName">
        <el-input v-model="queryParams.staffName" clearable placeholder="请输入" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['cld:overtime:add']" icon="el-icon-plus" plain size="mini" type="primary" @click="handleAdd">新增加班</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="overtimeList" border>
      <el-table-column align="center" label="加班项目" prop="projectName" width="180px;"/>
      <el-table-column align="center" label="加班类型" prop="overtimeType" width="120px;">
        <template slot-scope="scope">
          <dict-tag :options="overtimeTypeOptions" :value="scope.row.overtimeType"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="加班性质" prop="overtimeCategory" width="120px;">
        <template slot-scope="scope">
          <dict-tag :options="overtimeCategoryOptions" :value="scope.row.overtimeCategory"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="加班人" prop="staffNameArr" width="120px;"/>
      <el-table-column align="center" label="加班开始时间" prop="startTime" width="180px;">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="加班结束时间" prop="endTime" width="180px;">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="加班费" prop="overtimeMoney" width="120px;">
        <template slot-scope="scope">
          <span>{{ toMoney(scope.row.overtimeMoney) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="提交人" prop="createName" width="120px;"/>
      <el-table-column align="center" label="发起时间" prop="createTime" width="180px;"/>
      <el-table-column align="center" label="已审核/总条数" prop="isExamineCount" width="120px;">
        <template slot-scope="scope">
          <span v-if="scope.row.isExamineCount == scope.row.examineCount" style="color:forestgreen;">{{scope.row.isExamineCount}}/{{scope.row.examineCount}}</span>
          <span v-if="scope.row.isExamineCount < scope.row.examineCount" style="color:red;">{{scope.row.isExamineCount}}/{{scope.row.examineCount}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="已确认/总条数" prop="isConfirmCount" width="120px;">
        <template slot-scope="scope">
          <span v-if="scope.row.isConfirmCount == scope.row.examineCount" style="color:forestgreen;">{{scope.row.isConfirmCount}}/{{scope.row.examineCount}}</span>
          <span v-if="scope.row.isConfirmCount < scope.row.examineCount" style="color:red;">{{scope.row.isConfirmCount}}/{{scope.row.examineCount}}</span>
        </template>
      </el-table-column>
      <el-table-column label="加班说明" prop="remark"/>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="100px;">
        <template slot-scope="scope">
          <el-button v-hasPermi="['cld:overtime:edit']" size="mini" type="text" @click="handleUpdate(scope.row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum" :total="total" @pagination="getList"/>

    <!-- 添加或修改加班管理对话框 -->
    <el-dialog :close-on-click-modal="false" :visible.sync="open" append-to-body title="加班管理" width="50%">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="mini">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="加班类别" prop="overtimeMoney">
              <el-input v-model="form.overtimeMoney" class="input-with-select" placeholder="请输入">
                <el-select slot="prepend" v-model="form.overtimeCategory" placeholder="请选择">
                  <el-option v-for="item in overtimeCategoryOptions" :key="item.value" :label="item.label"
                             :value="parseInt(item.value)"></el-option>
                </el-select>
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="加班类型" prop="overtimeType">
              <el-select :disabled="form.overtimeId" v-model="form.overtimeType" placeholder="请选择">
                <el-option v-for="item in overtimeTypeOptions" :key="item.value" :label="item.label"
                           :value="parseInt(item.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="加班项目" prop="projectId">
              <el-select filterable :disabled="form.overtimeId" v-model="form.projectId" placeholder="请选择">
                <el-option v-for="item in projectOptions" :key="item.projectId" :label="item.projectName"
                           :value="item.projectId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col v-if="form.overtimeType == 2" :span="8">
            <el-form-item label="调出项目" prop="newProjectId">
              <el-select filterable :disabled="form.overtimeId" v-model="form.newProjectId" placeholder="请选择">
                <el-option v-for="item in projectOptions" :key="item.projectId" :label="item.projectName"
                           :value="item.projectId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="加班时间" prop="daterange">
              <el-date-picker :disabled="form.overtimeId" v-model="form.daterange" end-placeholder="结束日期" range-separator="至"
                              start-placeholder="开始日期"
                              type="datetimerange">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="加班说明" prop="remark">
              <el-input :disabled="form.overtimeId" v-model="form.remark" :rows="2" placeholder="请输入" type="textarea"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!form.overtimeId" :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button :disabled="!form.projectId" icon="el-icon-plus" plain size="mini" type="primary" @click="handleAddStaff">添加员工</el-button>
          </el-col>
        </el-row>
        <el-table :data="form.detailsList" border>
          <el-table-column align="center" label="岗位名称" prop="projectPostId">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.cld_project_post" :value="scope.row.projectPostId"/>
            </template>
          </el-table-column>
          <el-table-column align="center" label="姓名" prop="staffName"/>
          <el-table-column align="center" label="职务" prop="projectDuitsName">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.cld_project_duits" :value="scope.row.projectDuitsName"/>
            </template>
          </el-table-column>
          <el-table-column align="center" label="性别" prop="staffSex"/>
          <el-table-column align="center" label="年龄">
            <template slot-scope="scope">
              {{ calculateAge(scope.row.staffIdcard) }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="联系电话" prop="staffPhone"/>
          <el-table-column align="center" label="确认状态">
            <template slot-scope="scope">
              <el-tag type="danger" v-if="scope.row.isConfrim == 0">未确认</el-tag>
              <el-tag type="success" v-if="scope.row.isConfrim == 1">已确认</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="审核状态" prop="isExamine" >
            <template slot-scope="scope">
              <el-tag v-if="scope.row.isExamine == 0" type="info">未审核</el-tag>
              <el-tag v-if="scope.row.isExamine == 1" type="success">已审核</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="审核人" prop="examineUserName" />
          <el-table-column align="center" label="审核时间" prop="examineTime" />
          <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
            <template slot-scope="scope">
              <el-button v-if="!form.overtimeId" size="mini" type="text" @click="handleDeleteStaff(scope.row)">移除</el-button>
              <el-button v-if="scope.row.isConfrim == 1 && scope.row.attendanceId"  size="mini" type="text" @click="handleViewAtt(scope.row)">查看打卡</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择人员 -->
    <el-dialog :close-on-click-modal="false" :destroy-on-close="true" :visible.sync="isStaffOpen" append-to-body title="选择人员"
               width="70%">
      <SelectedStaff v-if="isStaffOpen" :isMultiple="true" :isProject="false" :params="{ notStaffIds: notStaffIds.join(','), staffStatus: 2, projectId: form.overtimeType == 2 ? form.newProjectId : form.projectId }"
                     @multipleInput="handleStaffSelected">
      </SelectedStaff>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSelectedStaff">确 定</el-button>
        <el-button @click="isStaffOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" :visible.sync="attOpen" title="查看打卡" width="500px">
      <el-form ref="form" :model="attList" label-position="top" label-width="80px" size="mini">
        <el-row v-for="item in attList" :key="form.attendanceId" :gutter="20">
          <el-col :span="6">
            <el-form-item :label="parseTime(item.attendanceDate, '{y}-{m}-{d}')">
            </el-form-item>
          </el-col>
          <div v-if="item.isInThisProject == 1 ">
            <el-col :span="8">
              <el-form-item label="加班开始时间">
                <el-time-picker v-model="item.thisStartTime" format='HH:mm' value-format='HH:mm'>
                </el-time-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="加班结束时间">
                <el-time-picker v-model="item.thisEndTime" format='HH:mm' value-format='HH:mm'>
                </el-time-picker>
              </el-form-item>
            </el-col>
          </div>
          <div v-if="item.isOutExtProject == 1">
            <el-col :span="8">
              <el-form-item label="加班开始时间">
                <el-time-picker v-model="item.extStartTime" format='HH:mm' value-format='HH:mm'>
                </el-time-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="加班结束时间">
                <el-time-picker v-model="item.extEndTime" format='HH:mm' value-format='HH:mm'>
                </el-time-picker>
              </el-form-item>
            </el-col>
          </div>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onSubmit">通 过</el-button>
        <el-button @click="attOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addOvertime, auditOvertime, getOvertime, listOvertime, updateOvertime} from "@/api/cld/overtime";
import {listAttendance} from "@/api/cld/attendance";
import analyze from './analyze.vue';
import {getList} from '@/api/cld/project'
import {overtimeCategoryOptions, overtimeTypeOptions} from '@/assets/staticDict'
import SelectedStaff from '@/views/cld/staff/selectedStaff';

export default {
  name: "Overtime",
  dicts: ['cld_project_post', 'cld_project_duits'],
  components: {analyze, SelectedStaff},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 加班管理表格数据
      overtimeList: [],
      // 是否显示弹出层
      open: false,
      // 员工选择
      isStaffOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        projectName: null,
        overtimeType: null,
        overtimeMonth: null,
        staffName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        overtimeMoney: [
          {required: true, message: "请输入加班金额", trigger: "blur"}
        ],
        overtimeType: [
          {required: true, message: "请选择加班类型", trigger: "change"}
        ],
        projectId: [
          {required: true, message: "请选择加班项目", trigger: "change"}
        ],
        newProjectId: [
          {required: true, message: "请选择调出项目", trigger: "change"}
        ],
        daterange: [
          {required: true, message: "请输入加班时间", trigger: "blur"}
        ]
      },
      // 加班金额类型
      overtimeCategoryOptions: overtimeCategoryOptions,
      // 加班类型
      overtimeTypeOptions: overtimeTypeOptions,
      // 项目列表
      projectOptions: [],
      // 考勤记录
      attList: [],
      currRow: {},
      attOpen: false,
      overTimeDetailsId:"",
      overtimeId:0,
      staffId:"",
    };
  },
  created() {
    this.getList();
    this.handleGetProjectList();
  },
  methods: {
    /** 查询加班管理列表 */
    getList() {
      this.loading = true;
      listOvertime(this.queryParams).then(response => {
        this.overtimeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 查询项目列表
    handleGetProjectList() {
      getList({
        projectStatus: 2
      }).then(res => {
        this.projectOptions = res.data;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        overtimeCategory: 1,
        startTime: null,
        endTime: null,
        detailsList: [],
        daterange: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.overtimeId = row.overtimeId || this.ids
      this.staffId = row.staffIdArr;
      const params = {overtimeId:this.overtimeId,staffIds:this.staffId};
      this.loadOverTimeDetails(params);
      this.open = true;
    },
    // 查看打卡
    handleViewAtt(row) {
      listAttendance({
        params: {
          attendanceIds: row.attendanceId
        }
      }).then(res => {
        this.currRow = row;
        this.attList = res.rows;
        this.attOpen = true;
      })
    },
    // 审核考勤打卡
    onSubmit() {
      auditOvertime(this.currRow).then(res => {
        this.$modal.msgSuccess("操作成功");
        this.attOpen = false;
        const params = {overtimeId:this.overtimeId,staffIds:this.staffId};
        this.loadOverTimeDetails(params);
        this.getList();
      })
    },
    // 加载加班明细表格
    loadOverTimeDetails(params){
      getOvertime(params).then(response => {
        this.form = response.data;
        let daterange = [this.parseTime(this.form.startTime), this.parseTime(this.form.endTime)];
        this.$set(this.form, 'daterange', daterange)
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log(this.form.daterange)
          this.form.startTime = this.parseTime(this.form.daterange[0]);
          this.form.endTime = this.parseTime(this.form.daterange[1]);
          if (this.form.overtimeId != null) {
            updateOvertime(this.form).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.open = false;
              this.getList();
            });
          } else {
            if (this.form.detailsList.length == 0) {
              this.$message.error('请选择加班员工');
              return;
            }
            addOvertime(this.form).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 添加员工
    handleAddStaff() {
      // 筛选已选择人员
      this.notStaffIds = this.form.detailsList.map(item => item.staffId);
      this.isStaffOpen = true;
    },
    // 员工选择监听
    handleStaffSelected(e) {
      this.temporaryList = e;
    },
    // 员工确认选择
    submitSelectedStaff() {
      this.temporaryList.forEach(item => {
        this.form.detailsList.push({
          ...item,
          staffId: item.staffId,
          projectPostId: item.projectPostName
        })
      })
      this.isStaffOpen = false;
    },
    // 移除员工
    handleDeleteStaff(row) {
      const index = this.form.detailsList.indexOf(row);
      if (index > -1) {
        this.form.staffList.splice(index, 1);
      }
    },
  }
};
</script>
<style scoped>
.el-select {
  width: 100%;
}

.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}

.el-input-group__prepend .el-select {
  width: 90px;
}
</style>
